// account的html 组件
import { Input, Select, AutoComplete, Transfer, Form, Button } from "antd";
import React, { useState, useEffect, forwardRef } from 'react';

const { Option } = Select;

export class EmailInput extends React.Component {
    // 自定义 Form.Item 元素
    constructor(props) {
        super(props);
        this.state = {
            data: []
        }
    }

    onSearch = searchText => {
        this.setState({
            data: !searchText ? [] : [searchText, `${searchText}@qq.com`, `${searchText}@163.com`],
        });
    };

    render() {

        return (
            <AutoComplete
                dataSource={this.state.data}
                value={this.props.value}
                onSearch={this.onSearch}
                onChange={value => this.props.onChange(value)}
                // onSelect={() =>{}}
                style={{ width: '100%' }}
            />
        );
    }
}

export const mySelect = (optionArr = [], args = { style: { width: '100%' } }, setPowerIndex ) => {

    const options = [];
    optionArr.forEach((item, i) => {
        options.push(<Option key={i} value={item.value}>{item.text}</Option>)
    })

    return <Select {...args} onChange={(value) => setPowerIndex && setPowerIndex(value)}>{options}</Select>
}

export class MyTransfer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            data: [],
            targetKeys: [],
            removeKeys: [],
        };
    }

    initTargetKeys = async () => {
        const { results = [] } = await this.props.initMethod({ id: this.props.value }, true);
        if (results) {
            const gUId = [];
            results.forEach(item => {
                item.id && gUId.push(item.id);
            })
            gUId.sort((a, b) => a - b);
            this.setState({ targetKeys: gUId });
        }
        // console.log("==>> initTargetKeys:", results, gUId)
    }

    getData = async () => {
        const { results = [] } = await this.props.reqMethod({}, true);
        const resData = [];
        const params = this.props.params || [];
        results.forEach((item, i) => {
            // console.log("===>> item", item)
            const args = {};
            params.forEach(para => {
                const { newKey, resKey } = para;
                args[newKey] = item[resKey];
            })
            resData.push(args);
            // resData.push({
            //     key: item.id,
            //     title: item.username,
            //     description: item.email,
            // });
        })
        this.setState({ data: resData});
        // console.log("==>> response", resData)
    }

    componentDidMount() {
        this.initTargetKeys();
        this.getData();
    }

    onChange = (targetKeys, direction, moveKeys)  => {
        this.setState({ targetKeys});
        // console.log('==>> targetKeys', targetKeys, direction, moveKeys)
        this.props.onChange({ handMethod: this.props.extraMethod, values: { direction, moveKeys } });
    }

    render() {
        return (
            <Transfer
                dataSource={this.state.data}
                value={this.props.value}
                // showSearch
                // filterOption={this.filterOption}
                targetKeys={this.state.targetKeys}
                onChange={this.onChange}
                // onSearch={this.handleSearch}
                render={item => item.title}
            />
        );
    }
}


const SelectForm = props => {

    const { form, name = '', optionArr = [], args = {}, setPowerIndex } = props;
    const initValue = args['defaultValue'];
    const selectArgs = { ...args };
    delete selectArgs['defaultValue'];

    return (
        optionArr.length &&
        form.getFieldDecorator(name, {
            initialValue: initValue ? initValue : optionArr[0].value,
        })(mySelect(optionArr, selectArgs, setPowerIndex))
    );
}
const MySelectForm = Form.create()(SelectForm);

let BeforeInputAfter = (props, ref) => {

    const { 
        onChange: parentOnChange, beforeOptions = [], afterOptions = [], 
        beforeArgs = {}, afterArgs = {}, baseNumber = 1024, placeholder,
    } = props;
    const [powerIndex, setPowerIndex] = useState(afterArgs.defaultValue || 0);
    const [value, setValue] = useState('');

    const before = beforeOptions.length
        ? <MySelectForm name="before" optionArr={beforeOptions} args={beforeArgs} setPowerIndex={setPowerIndex} /> : null;
    const after = afterOptions.length
        ? <MySelectForm name="after" optionArr={afterOptions} args={afterArgs} setPowerIndex={setPowerIndex} /> : null;

    const handleChange = e => {
        const { value:changeValue } = e.target;
        setValue(changeValue);
        Number(changeValue) && parentOnChange(parseInt(changeValue) * Math.pow(baseNumber, powerIndex));
        // console.log("==>> parentOnChange", changeValue, powerIndex)
    }

    useEffect(() =>{
        console.log("==>> props.value", props.value)
        if (Array.isArray(props.value)) {
            setValue(props.value[0]);
            const unit = props.value.pop();
            setPowerIndex(unit);
            afterArgs['defaultValue'] = unit;
        } 
        else {
            !isNaN(Number(props.value)) && setValue(props.value);
        }
    }, [])

    useEffect(() => {
        // console.log("==>> powerIndex", powerIndex, value)
        Number(value) && parentOnChange(parseInt(value) * Math.pow(baseNumber, powerIndex))
    }, [powerIndex])

    return (
        <span ref={ref}>
            <Input
                value={value}  // 界面显示的值。
                onChange={handleChange}  // form提交时，传递的值。
                addonBefore={before}
                addonAfter={after}
                placeholder={placeholder ? placeholder : "使用默认值。"}
            />
        </span>
    );
}

BeforeInputAfter = forwardRef(BeforeInputAfter)
export {BeforeInputAfter};